<template>
  <BaseFormField
    v-slot="{ isReadonly, fieldId }"
    :resource-name="resourceName"
    :field="field"
    :value="modelValue"
    :is-floating="isFloating"
  >
    <FormFieldGroup
      :field="field"
      :label="field.label"
      :field-id="fieldId"
      :validation-errors="validationErrors"
    >
      <div class="relative">
        <div
          v-if="field.https"
          class="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3"
        >
          <span
            class="text-sm text-neutral-500 dark:text-neutral-300"
            v-text="'https://'"
          />
        </div>

        <IFormInput
          :id="fieldId"
          :model-value="modelValue"
          :disabled="isReadonly"
          :name="field.attribute"
          type="url"
          v-bind="field.attributes"
          :class="['pr-10', { 'pl-16': field.https }]"
          @update:model-value="updateModelValue"
        />

        <div class="absolute inset-y-0 right-0 flex items-center pr-3">
          <a
            :href="modelValue || '#'"
            :class="[
              !modelValue ? 'text-neutral-400 dark:text-neutral-300' : 'link',
              { 'pointer-events-none': !modelValue },
            ]"
          >
            <Icon icon="Link" class="h-5 w-5" />
          </a>
        </div>
      </div>
    </FormFieldGroup>
  </BaseFormField>
</template>

<script setup>
import isNil from 'lodash/isNil'

import FormFieldGroup from '../FormFieldGroup.vue'

const props = defineProps({
  field: { type: Object, required: true },
  modelValue: {},
  resourceName: String,
  resourceId: [String, Number],
  validationErrors: Object,
  isFloating: Boolean,
})

const emit = defineEmits(['update:modelValue', 'set:initialValue'])

function updateModelValue(value) {
  emit('update:modelValue', value)
}

function setInitialValue() {
  emit('set:initialValue', !isNil(props.field.value) ? props.field.value : '')
}

setInitialValue()
</script>
